#!/bin/bash
# Author: Daniele Rondina, geaaru@sabayonlinux.org
# Initialize a repository for luet specs.
# License: MIT

LUET_REPO_NAME="${LUET_REPO_NAME:-}"
LUET_REPO_CACHE="${LUET_REPO_CACHE:-}"
LUET_REPO_MULTIARCH="${LUET_REPO_MULTIARCH:-0}"
LUET_REPO_DESCR="${LUET_REPO_DESCR:-}"
LUET_REPO_DIR="${LUET_REPO_DIR:-.}"
LUET_REPO_ARCH="${LUET_REPO_ARCH:-amd64}"
QUIET="${QUIET:-0}"

summary () {
  echo "Creating Luet Repository Tree:

LUET_REPO_NAME:  ${LUET_REPO_NAME}
LUET_REPO_CACHE: ${LUET_REPO_CACHE}
LUET_REPO_MULTIARCH: ${LUET_REPO_MULTIARCH}
LUET_REPO_DESCR: ${LUET_REPO_DESCR}
LUET_REPO_DIR: ${LUET_REPO_DIR}
LUET_REPO_ARCH: ${LUET_REPO_ARCH}
"
  return 0
}

initenv () {

  local makefile_template=""

  if [[ ! -d "${LUET_REPO_DIR}" ]] ; then
    mkdir ${LUET_REPO_DIR} || {
      echo "Error on create directory ${LUET_REPO_DIR}."
      return 1
    }
  fi

  # Check write permission
  touch ${LUET_REPO_DIR}/.tmp || {
    echo "Directory ${LUET_REPO_DIR} is not writable."
    return 1
  }
  rm ${LUET_REPO_DIR}/.tmp


  if [ "${LUET_REPO_MULTIARCH}" = "1" ] ; then
    mkdir -p ${LUET_REPO_DIR}/${LUET_REPO_ARCH}/packages/
    touch ${LUET_REPO_DIR}/${LUET_REPO_ARCH}/packages/.keep
    mkdir -p ${LUET_REPO_DIR}/multi-arch/packages/
    touch ${LUET_REPO_DIR}/multi-arch/packages/.keep

    makefile_template="
BACKEND?=docker
CONCURRENCY?=1
CI_ARGS?=
PACKAGES?=

# Abs path only. It gets copied in chroot in pre-seed stages
export LUET?=/usr/bin/luet
export ROOT_DIR:=\$(shell dirname \$(realpath \$(lastword \$(MAKEFILE_LIST))))
DESTINATION?=\$(ROOT_DIR)/build
COMPRESSION?=gzip
export COMMON_TREE?=\${ROOT_DIR}/multi-arch/packages
export TREE?=\$(ROOT_DIR)/${LUET_REPO_ARCH}/packages
REPO_CACHE?=${LUET_REPO_CACHE}
export REPO_CACHE
BUILD_ARGS?=--pull --no-spinner
SUDO?=
VALIDATE_OPTIONS?=-s
ARCH?=amd64

ifneq (\$(strip \$(REPO_CACHE)),)
	BUILD_ARGS+=--image-repository \$(REPO_CACHE)
endif

.PHONY: all
all: deps build

.PHONY: deps
deps:
	@echo \"Installing luet\"
	go get -u github.com/mudler/luet

.PHONY: clean
clean:
	\$(SUDO) rm -rf build/ *.tar *.metadata.yaml

.PHONY: build
build: clean
	mkdir -p \$(DESTINATION)
	\$(SUDO) \$(LUET) build \$(BUILD_ARGS) --tree=\$(COMMON_TREE) --tree=\$(TREE) \$(PACKAGES) --destination \$(DESTINATION) --backend \$(BACKEND) --concurrency \$(CONCURRENCY) --compression \$(COMPRESSION)

.PHONY: build-all
build-all: clean
	mkdir -p \$(DESTINATION)
	\$(SUDO) \$(LUET) build \$(BUILD_ARGS) --tree=\$(COMMON_TREE) --tree=\$(TREE) --full --destination \$(DESTINATION) --backend \$(BACKEND) --concurrency \$(CONCURRENCY) --compression \$(COMPRESSION)

.PHONY: rebuild
rebuild:
	\$(SUDO) \$(LUET) build \$(BUILD_ARGS) --tree=\$(COMMON_TREE) --tree=\$(TREE) \$(PACKAGES) --destination \$(DESTINATION) --backend \$(BACKEND) --concurrency \$(CONCURRENCY) --compression \$(COMPRESSION)

.PHONY: rebuild-all
rebuild-all:
	\$(SUDO) \$(LUET) build \$(BUILD_ARGS) --tree=\$(COMMON_TREE) --tree=\$(TREE) --full --destination \$(DESTINATION) --backend \$(BACKEND) --concurrency \$(CONCURRENCY) --compression \$(COMPRESSION)

.PHONY: create-repo
create-repo:
	\$(SUDO) \$(LUET) create-repo --tree \"\$(TREE)\" --tree \"\$(COMMON_TREE)\" \\
    --output \$(DESTINATION) \\
    --packages \$(DESTINATION) \\
    --name \"${LUET_REPO_NAME}\" \\
    --descr \"${LUET_REPO_DESCR} \$(ARCH)\" \\
    --urls \"http://localhost:8000\" \\
    --tree-compression \$(COMPRESSION) \\
    --tree-filename tree.tar \\
    --meta-compression \$(COMPRESSION) \\
    --type http

.PHONY: serve-repo
serve-repo:
	LUET_NOLOCK=true \$(LUET) serve-repo --port 8000 --dir \$(DESTINATION)

auto-bump:
	TREE_DIR=\$(ROOT_DIR) \$(LUET) autobump-github

autobump: auto-bump

validate:
	\$(LUET)  tree validate --tree \$(TREE) --tree=\$(COMMON_TREE) \$(VALIDATE_OPTIONS)
"

  else
    mkdir -p ${LUET_REPO_DIR}/packages/
    touch ${LUET_REPO_DIR}/packages/.keep


    makefile_template="
BACKEND?=docker
CONCURRENCY?=1
CI_ARGS?=
PACKAGES?=

# Abs path only. It gets copied in chroot in pre-seed stages
export LUET?=/usr/bin/luet
export ROOT_DIR:=\$(shell dirname \$(realpath \$(lastword \$(MAKEFILE_LIST))))
DESTINATION?=\$(ROOT_DIR)/build
COMPRESSION?=gzip
CLEAN?=false
export TREE?=\$(ROOT_DIR)/packages
REPO_CACHE?=${LUET_REPO_CACHE}
export REPO_CACHE
BUILD_ARGS?=--pull --no-spinner
SUDO?=
VALIDATE_OPTIONS?=-s
ARCH?=amd64

ifneq (\$(strip \$(REPO_CACHE)),)
	BUILD_ARGS+=--image-repository \$(REPO_CACHE)
endif

.PHONY: all
all: deps build

.PHONY: deps
deps:
	@echo \"Installing luet\"
	go get -u github.com/mudler/luet

.PHONY: clean
clean:
	\$(SUDO) rm -rf build/ *.tar *.metadata.yaml

.PHONY: build
build: clean
	mkdir -p \$(DESTINATION)
	\$(SUDO) \$(LUET) build \$(BUILD_ARGS) --tree=\$(TREE) \$(PACKAGES) --destination \$(DESTINATION) --backend \$(BACKEND) --concurrency \$(CONCURRENCY) --compression \$(COMPRESSION)

.PHONY: build-all
build-all: clean
	mkdir -p \$(DESTINATION)
	\$(SUDO) \$(LUET) build \$(BUILD_ARGS) --tree=\$(TREE) --full --destination \$(DESTINATION) --backend \$(BACKEND) --concurrency \$(CONCURRENCY) --compression \$(COMPRESSION)

.PHONY: rebuild
rebuild:
	\$(SUDO) \$(LUET) build \$(BUILD_ARGS) --tree=\$(TREE) \$(PACKAGES) --destination \$(DESTINATION) --backend \$(BACKEND) --concurrency \$(CONCURRENCY) --compression \$(COMPRESSION)

.PHONY: rebuild-all
rebuild-all:
	\$(SUDO) \$(LUET) build \$(BUILD_ARGS) --tree=\$(TREE) --full --destination \$(DESTINATION) --backend \$(BACKEND) --concurrency \$(CONCURRENCY) --compression \$(COMPRESSION)

.PHONY: create-repo
create-repo:
	\$(SUDO) \$(LUET) create-repo --tree \"\$(TREE)\" \\
    --output \$(DESTINATION) \\
    --packages \$(DESTINATION) \\
    --name \"${LUET_REPO_NAME}\" \\
    --descr \"${LUET_REPO_DESCR} \$(ARCH)\" \\
    --urls \"http://localhost:8000\" \\
    --tree-compression \$(COMPRESSION) \\
    --tree-filename tree.tar \\
    --meta-compression \$(COMPRESSION) \\
    --type http

.PHONY: serve-repo
serve-repo:
	LUET_NOLOCK=true \$(LUET) serve-repo --port 8000 --dir \$(DESTINATION)

auto-bump:
	TREE_DIR=\$(ROOT_DIR) \$(LUET) autobump-github

autobump: auto-bump

validate:
	\$(LUET)  tree validate --tree \$(TREE) \$(VALIDATE_OPTIONS)
"
  fi

  echo "${makefile_template}" > ${LUET_REPO_DIR}/Makefile

  return 0
}

main () {


  parse_args () {

    _help () {
      echo "Copyright (c) 2020 Luet Extensions

luet initenv [opts]

Initialize a repository tree for build Luet packages:

  * create Makefile
  * empty packages tree(s)

Example:

  $> luet initenv -- --name foo-repo --image-repository <mydockeruser>/<cache-prefix>

Available options:

--help|-h                             Show this help message.
--name <REPO_NAME>                    Name of the repository.
--image-repository <REPO_CACHE>       Set repository image cache.
--multi-arch                          Setup a multi arch tree. Default is single arch.
--descr <DESCR>                       Description of the repository.
--dir <DIR>                           Path where create the repository tree. Default \"${LUET_REPO_DIR}\".
--arch <ARCH>                         Default build arch. Default \"${LUET_REPO_ARCH}\".
--quiet                               Quiet output.
"
      return 0
    }

    if [ $# -eq 0 ] ; then
      _help
      exit 1
    fi

    local short_opts="h"
    local long_opts="help name image-repository multi-arch descr dir arch quiet"
    $(set -- $(getopt -u -q -a -o "${short_opts}" -l "${long_opts}" -- "$@"))

    while [ $# -gt 0 ] ; do

      case "$1" in
        -h|--help)
          _help
          exit 1
          ;;
        --name)
          LUET_REPO_NAME=$2
          shift
          ;;
        --image-repository)
          LUET_REPO_CACHE=$2
          shift
          ;;
        --multi-arch)
          LUET_REPO_MULTIARCH=1
          ;;
        --descr)
          LUET_REPO_DESCR=$2
          shift
          ;;
        --dir)
          LUET_REPO_DIR=$2
          shift
          ;;
        --arch)
          LUET_REPO_ARCH=$2
          shift
          ;;
        --quiet)
          QUIET=1
          ;;
        --)
          ;;
        *)
          echo "Invalid parameter $1"
          exit 1
          ;;
      esac

      shift
    done

    if [ -z "${LUET_REPO_NAME}" ] ; then
      echo "ERROR: Missing repository name"
      exit 1
    fi

    return 0
  }

  parse_args "$@"

  unset -f parse_args

  if [ "${QUIET}" == "0" ] ; then
    summary
  fi

  initenv || return 1

  if [ "${QUIET}" == "0" ] ; then
    echo "Repository ${LUET_REPO_NAME} created correctly."
  fi

  return 0
}

main "$@"
exit $?
